package com.adcc.foc.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * Created by houxy on 2016/8/9.
 * JWT加密解密token的工具类
 */
public class TokenUtil {

    //自定义密匙
    private static final String SECRET_KEY = "adcc";

    /**
     * 将用户名密码加密
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public static String getJWTString(String username, String password) {
        String jwtString = "Bearer ";
        jwtString += Jwts.builder().
                setIssuedAt(new Date()).claim("username", username).claim("password", password).
                signWith(SignatureAlgorithm.HS256, SECRET_KEY).
                compact();
        return jwtString;
    }

    /**
     * 将接受到的Token解密
     *
     * @param token
     * @return
     */
    public static String getJWTMessage(String token) {
        String str = null;
        if (token != null && !"".equals(token)) {
            Claims claims = Jwts.parser().setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token.substring(7)).getBody();
            str = (String) claims.get("username");
            str += "_" + (String) claims.get("password");
        }
        return str;
    }
}
